<template>
	<view class="pick-video">
		<view class="page1" v-if="pageTabbarAc == 0">
			<view class="main-tabbar">
				<view :class="['tabbar-item-1', tabbarAc == item.id ? 'ac' : '']" v-for="(item, index) in tabbarList" @click="changeTabbarAc({ item, index })" :key="item.id">
					<view class="text">{{ item.text }}</view>
				</view>
			</view>
			<view class="main-tabbar" v-if="tabbarAc == 1">
				<view :class="['tabbar-item', tabbarAc2 == item.id ? 'ac' : '']" v-for="(item, index) in tabbarList2" :key="item.id" @click="changeTabbarAc2({ item, index })">
					<view class="text">{{ item.classifyName }}</view>
				</view>
			</view>
			<view class="main-content">
				<view class="contentList" v-if="tabbarAc == 1" @scroll="contentListScroll" ref="videoContentList">
					<view class="contentItem" v-for="(item, index) in yushe" @click="pickContentItem({ item, index })" :key="item.id">
						<image class="pic" :src="pageItem.ac == 5 ? item.theCover : ''" mode="heightFix"></image>
						<view class="bottom">
							<view class="name">{{ item.matterName }}</view>
						</view>
					</view>
				</view>
				<view class="contentList" v-if="tabbarAc == 2" @scroll="contentListScroll" ref="videoContentList">
					<view class="contentItem first" :style="{ '--height-val': 'calc(30vh - 9vw)' }" @click="addContentItem()">
						<image class="pic add" :src="imgPath + 'createAvatar/changjing-add.svg'" mode="heightFix"></image>
						<view class="bottom">
							<view class="name">{{ "本地上传" }}</view>
						</view>
					</view>
					<view class="contentItem" v-for="(item, index) in geren" @click="pickContentItem({ item, index })" :key="item.id" :style="{ '--height-val': 'calc(30vh - 9vw)' }">
						<video class="vid" :src="pageItem.ac == 5 ? item.matterUrl : ''" :controls="false"></video>
						<!-- <image class="pic" :src="pageItem.ac == 5?item.matterUrl:''" mode="heightFix"></image> -->
						<view class="bottom">
							<view class="name">{{ item.matterName }}</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="page2" v-if="pageTabbarAc == 1">
			<view class="main-edit">
				<view class="btns">
					<view class="btn-item" @tap="del()">
						<image class="icon" :src="imgPath + 'createAvatar/del.svg'" mode=""></image>
						<view class="text">删除</view>
					</view>
					<view class="btn-item" @tap="changeZIndex(1)">
						<image class="icon" :src="imgPath + 'createAvatar/up.svg'" mode=""></image>
						<view class="text">层级上移</view>
					</view>
					<view class="btn-item" @tap="changeZIndex(-1)">
						<image class="icon" :src="imgPath + 'createAvatar/up.svg'" mode="" style="transform: rotate(180deg)"></image>
						<view class="text">层级下移</view>
					</view>
				</view>
			</view>
			<view class="textStyle-item">
				<view class="label">音量</view>
				<view class="r-c slider-box">
					<slider :value="volume" @change="changeElVolume" step="1" :min="0" :max="100" show-value />
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import * as api from "@/api/createVideo.js";
import axios from "axios";
let timer = null;
import { tools } from "../../../../utils/util";
export default {
	props: {
		show: {
			type: Boolean,
			default: false
		},
		promiseRes: {
			type: Object | Function,
			default() {
				return null;
			}
		},
		currInd: {
			type: Number,
			default: -1
		},
		scene2: {
			type: Array,
			default() {
				return [];
			}
		},
		pageItem: {
			type: Object,
			default() {
				return {};
			}
		}
	},
	data() {
		return {
			imgPath: tools.imgPath,
			pageTabbarAc: 0,
			pageTabbarList: [],
			tabbarAc: 1,
			tabbarList: [],
			tabbarAc2: null,
			tabbarList2: [],
			yushe: [],
			yusheCurrent: 1,
			yusheSize: 10,
			yusheTotal: null,
			geren: [],
			gerenCurrent: 1,
			gerenSize: 999,
			gerenTotal: null,
			uploadFileSize: 200,
			contentList: [],
			volume: 0
		};
	},
	async created() {
		this.initPageTabbarList();
		this.initTabbarList();
		let next = await this.initGetData();
		if (this.promiseRes) {
			this.promiseRes(true);
		}
	},
	methods: {
		// 本地上传
		addContentItem() {
			const that = this;
			uni.chooseFile({
				count: 1, //默认100
				extension: [".avi", ".mp4", ".mkv", ".mov", ".flv", ".rmvb", "3gp"],
				success: (res) => {
					const tempFilePaths = res.tempFilePaths;
					let file = res.tempFiles[0];
					if (!file.type.includes("video")) {
						return tools.easyToast("请选择视频频文件！");
					}
					let name = file.name;
					if (!/^[\u4e00-\u9fa5a-zA-Z0-9\.\-]+$/.test(name)) {
						return tools.easyToast("文件名不能包含符号，只能是文字或数字");
					}
					if (file.size / 1024 / 1024 > this.uploadFileSize) {
						return tools.easyToast(`文件大小超过${this.uploadFileSize}M!`);
					}
					var oVideo = document.createElement("video");
					oVideo.setAttribute("src", res.tempFilePaths[0]);
					oVideo.addEventListener("canplay", async function (event) {
						let { videoHeight, videoWidth, duration } = event.target;
						if (duration < 1) {
							return this.$message("视频时长必须不少于1秒！");
						}
						let ossData = await api.postOSS({
							reqType: "mat_video",
							matName: name,
							payLoad: {
								matterValue: duration,
								height: videoHeight,
								wide: videoWidth
							}
						});
						let res = await that.getOSSApi_new(ossData, file, name);
						if (!res) return;
						that.geren = [];
						that.getDataApi2();
					});
				}
			});
		},
		//上传文件api
		async getOSSApi_new(ossData, file, name) {
			const that = this;
			let res = ossData;

			function getUUID() {
				let keyStr = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";
				keyStr = "xxxxxxxx-6xxx";
				return keyStr.replace(/[xy]/g, (c) => {
					return (c === "x" ? (Math.random() * 16) | 0 : "r&0x3" | "0x8").toString(16);
				});
			}
			const formData = new FormData();
			let url_name = "https://alleymall.oss-cn-guangzhou.aliyuncs.com";
			let key = res.data.dir + "/" + getUUID() + name;
			formData.append("policy", res.data.policy);
			formData.append("signature", res.data.signature);
			formData.append("ossaccessKeyId", res.data.accessid);
			formData.append("key", key);
			formData.append("dir", res.data.dir);
			formData.append("host", res.data.host);
			formData.append("expire", res.data.expire);
			formData.append("callback", res.data.callback);
			// formData.append('type', res.data.callback)
			formData.append("file", file);

			return axios
				.post(url_name, formData, {
					headers: {
						"Content-Type": "multipart/form-data"
					}
				})
				.then((response) => {
					let src = url_name + "/" + key;
					// console.log(src);
					// that.audioPlayerSrc = src;
					// console.log(response);
					return {
						...response,
						src
					};
				})
				.catch((error) => {
					console.log(error);
				});
		},
		// 滚动事件(做懒加载)
		contentListScroll(event) {
			const that = this;
			if (timer) clearTimeout(timer);
			timer = setTimeout(() => {
				let target = this.$refs.videoContentList.$el;
				if (target.scrollWidth - 5 < target.scrollLeft + target.offsetWidth) {
					if (that.tabbarAc == 1) {
						if (this.yusheTotal === this.yushe.length) return;
						this.yusheCurrent++;
						this.getDataApi();
					} else {
						if (this.gerenTotal === this.geren.length) return;
						this.gerenCurrent++;
						this.getDataApi2();
					}
				}
				clearTimeout(timer);
				timer = null;
			}, 300);
		},
		// 获取公共数据分类api
		async getSysmatTwoType() {
			const type = "video";
			let res = await api.getSysmatTwoType(type);
			if (!res) return;
			this.tabbarList2 = [
				{
					id: null,
					classifyName: "全部"
				},
				...res.data
			];
			this.tabbarAc2 = this.tabbarList2[0].id;
			return true;
		},
		// 获取公共数据api
		async getDataApi(_id) {
			_id = ["Null", "Number", "String"].includes(tools.myTypeOf(_id)) ? _id : this.tabbarAc2;
			let res = null;
			if (_id) {
				//获取分类数据
				let data = {
					oneid: _id,
					size: this.yusheSize,
					current: this.yusheCurrent,
					twoid: 2 //横屏1，竖屏2
				};
				res = await api.getVideoSysmat(data);
			} else {
				//获取全部数据
				let data = {
					type: "video",
					size: this.yusheSize,
					current: this.yusheCurrent,
					id: 2 //横屏1，竖屏2
				};
				res = await api.getVideoSysmatAll(data);
			}
			if (!res?.data?.records) {
				this.yushe = [];
				this.yusheTotal = null;
				return;
			}
			this.yusheTotal = res.data.total;
			let yushe = res.data.records.map((e) => ({
				...e,
				volume: this.volume,
				picSrc: e.theCover.replace("https://alleymall.oss-cn-guangzhou.aliyuncs.com/", `${location.origin}/assets/`) || null
			}));
			this.yushe = [...this.yushe, ...yushe];
			return true;
		},
		// 获取私有数据api
		async getDataApi2() {
			let res = await api.getUserSource("video");
			if (!res) return;
			this.geren = res.data.map((e) => ({
				...e,
				volume: this.volume,
				picSrc: e.matterUrl.replace("https://alleymall.oss-cn-guangzhou.aliyuncs.com/", `${location.origin}/assets/`) || null
			}));
			return true;
		},
		// 获取后端数据
		async initGetData() {
			let getData = new Promise(async (next) => {
				let flag = await this.getSysmatTwoType();
				if (!flag) return;
				let flag2 = await this.getDataApi();
				if (!flag2) return;
				next(true);
			});
			await Promise.all([getData]);
			return true;
		},
		// 初始化contentList
		initContentList() {
			this.contentList = matData.map((e) => ({
				...e,
				picSrc: e.theCover
			}));
		},
		// 初始化tabbarList
		initTabbarList() {
			this.tabbarList = [
				{
					text: "预设",
					id: 1
				},
				{
					text: "本地",
					id: 2
				}
			];
		},
		//初始化pageTabbarList
		initPageTabbarList() {
			this.pageTabbarList = [
				{
					text: "选择图片",
					id: 0
				},
				{
					text: "编辑图片",
					id: 1
				}
			];
			if (this.pageItem) {
				// console.log('初始化pageTabbarList',this.pageItem);
				this.pageTabbarAc = this.pageItem.pageAc;
			}
		},
		//切换页面类型
		changePageTabbarAc({ item, index }) {
			// if (this.pageTabbarAc == item.id) return;
			this.pageTabbarAc = item.id;
			if (this.pageTabbarAc == 0) {
				this.$emit("changeMyDH", 35);
			} else {
				this.$emit("changeMyDH", 16);
			}
		},
		// 切换类型
		changeTabbarAc({ item, index }) {
			this.tabbarAc = item.id;
			if (this.tabbarAc == 2) {
				//获取私有数据
				this.getDataApi2();
			}
		},
		//切换数据子类型
		changeTabbarAc2({ item, index }) {
			this.tabbarAc2 = item.id;
			this.yushe = [];
			this.yusheCurrent = 1;
			this.yusheTotal = null;
			this.getDataApi();
		},
		//选择item
		pickContentItem({ item, index }) {
			this.$emit("pickVideo", {
				item,
				index
			});
		},
		// 删除
		del() {
			this.$emit("removeEl", this.currInd);
		},
		// 修改层级
		changeZIndex(num) {
			if (this.currInd == null || this.currInd < 0) {
				return tools.easyToast("请先选择图片!");
				// if (index == -1) {
				// 	tools.easyToast('请先选择数字人!');
				// } else {
				// 	this.$emit('changeZIndex', this.currInd, num);
				// };
			} else {
				this.$emit("changeZIndex", this.currInd, num);
			}
		},
		// 修改视频音量
		changeElVolume(e) {
			this.volume = e.detail.value;
			this.$emit("changeElVolume", this.currInd, this.volume);
		}
	},
	watch: {
		["pageItem.ac"](val) {
			if (val != 5) return;
			this.changePageTabbarAc({
				item: {
					id: this.pageItem.pageAc
				}
			});
		}
	}
};
</script>

<style lang="scss">
.pick-video {
	padding: 5vw;
	display: flex;
	flex-direction: column;
	overflow: hidden;
	height: 100%;

	.page1 {
		display: flex;
		flex-direction: column;
		overflow: hidden;
		height: 100%;
	}

	.main-tabbar {
		display: -webkit-box;
		overflow: auto;

		.tabbar-item-1 {
			padding: 2vw;
			font-size: 32rpx;
			font-weight: 400;
			color: rgba(255, 255, 255, 1);
			display: flex;
			justify-content: center;
			align-items: center;

			&.ac {
				.text {
					color: rgba(0, 153, 127, 1);
					border-bottom: 2px solid rgba(243, 173, 51, 1);
				}
			}

			.text {
				padding-bottom: 2vw;
			}
		}

		.tabbar-item {
			padding: 0.5vw 1vw;
			color: rgba(255, 255, 255, 0.36);
			display: flex;
			justify-content: center;
			align-items: center;
			border-radius: 100vw;
			background: rgba(255, 255, 255, 0.125);
			margin: 0vw 5vw 2vw 0vw;
			min-width: 10vw;

			&.ac {
				border: 2px solid rgba(0, 153, 127, 1);

				.text {
					color: rgba(0, 153, 127, 1);
					font-weight: 700;
				}
			}

			.text {
				font-size: 24rpx;
				font-weight: 400;
			}
		}
	}

	.main-content {
		flex: 1;
		overflow: hidden;
		display: flex;

		.contentList {
			display: -webkit-box;
			overflow: auto;
			height: max-content;
			max-height: 100%;

			.contentItem {
				--height-val: calc(30vh - 22vw);
				width: max-content;
				height: var(--height-val);
				overflow: hidden;
				margin-right: 3vw;
				margin-bottom: 1.2vw;
				border-radius: 2vw;
				background: rgba(28, 43, 46, 1);
				display: flex;
				justify-content: center;
				align-items: center;
				position: relative;
				&.first {
					width: 30vw;
				}
				.pic {
					width: 100%;
					height: 100%;
					&.add {
						width: 30%;
						height: 30%;
					}
				}

				.tag {
					position: absolute;
					top: 0vw;
					left: 0vw;
					border-radius: 3vw 0vw 3vw 0vw;
					background: linear-gradient(270deg, rgba(0, 222, 185, 1) 0%, rgba(122, 255, 233, 1) 100%);
					font-size: 20rpx;
					font-weight: 400;
					color: rgba(22, 24, 30, 1);
					display: flex;
					justify-content: center;
					align-items: center;
					padding: 1vw 1.5vw;
				}

				.bottom {
					position: absolute;
					bottom: 0vw;
					width: 100%;
					height: 6vw;
					display: flex;
					justify-content: center;
					align-items: center;
					background: rgba(22, 24, 30, 0.7);
					font-size: 20rpx;
					font-weight: 400;
					color: rgba(204, 204, 204, 1);
				}
			}
		}
	}

	.page2 {
		.main-edit {
			.btns {
				display: flex;

				.btn-item {
					border: 1px solid #fff;
					display: flex;
					flex-direction: column;
					justify-content: center;
					align-items: center;
					min-width: 20vw;
					margin-right: 2vw;
					border-radius: 2vw;
					padding: 1vw;

					.icon {
						width: 5vw;
						height: 5vw;
						display: block;
					}
				}
			}
		}

		.textStyle-item {
			width: 100%;
			display: flex;
			align-items: center;
			padding: 2vw 0vw;

			.label {
			}

			.r-c {
				margin-left: 3vw;
				flex: 1;

				&.slider-box {
				}
			}
		}
	}
}
</style>
